package org.jeecg.modules.lock.job;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.door.entity.LwgyJointDoor;
import org.jeecg.modules.lock.service.LwgyDoorLockService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 门锁 -- 获取第三方房间列表，并存入到数据库中
 *
 * @author:MJ-BaBa
 * @date: 2021.07.15
 */

@Slf4j
public class getApartmentRoomListJob implements Job {

    private static final String CALLBACK_URL_SET_ENDPOINT = "https://server.hxjiot.com";// 接口地址
    @Autowired
    private LwgyDoorLockService doorLockService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            System.out.println("============进入定时器=============");
            long start1 = System.currentTimeMillis();

            String tokenId = doorLockService.getAuthentication();
            System.out.println("tokenId ========== " + tokenId);
            if (tokenId == null) {
                System.out.println("获取tokenId失败");
            }
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

            int startNum = 0; // 起始记录数
            int getNum = 30; // 每次获取的记录数
            List<Map<String, Object>> allRoomData = new ArrayList<>(); // 存储所有房间数据
            // 循环获取数据直到获取全部数据为止
            while (true) {
                // 构建请求体
                Map<String, Object> requestData = new HashMap<>();
                requestData.put("startNum", startNum);
                requestData.put("getNum", getNum);

                Map<String, Object> requestBodyMap = new HashMap<>();
                requestBodyMap.put("method", "apartmentRoomList");
                requestBodyMap.put("tokenId", tokenId);
                requestBodyMap.put("data", requestData);

                ObjectMapper objectMapper = new ObjectMapper();
                String requestBody = objectMapper.writeValueAsString(requestBodyMap);
                RequestBody body = RequestBody.create(mediaType, requestBody);

                // 构建请求
                Request request = new Request.Builder()
                        .url(CALLBACK_URL_SET_ENDPOINT)
                        .post(body)
                        .addHeader("Content-Type", "application/json")
                        .addHeader("Content-Version", "1.2")
                        .build();

                // 发起请求
                Response response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    // 解析响应
                    String jsonResponse = response.body().string();
                    Map<String, Object> responseData = objectMapper.readValue(jsonResponse, new TypeReference<HashMap<String, Object>>() {});
                    System.out.println("responseData  ========== " + responseData);
                    Map<String, Object> dataAll = (Map<String, Object>) responseData.get("data");
                    // 获取房间列表
                    List<Map<String, Object>> roomData = (List<Map<String, Object>>) dataAll.get("list");
                    System.out.println("roomData  ========== " + roomData);
                    allRoomData.addAll(roomData);

                    // 更新起始记录数
                    startNum += getNum;

                    // 检查是否还有更多数据
                    int listSum = (int) dataAll.get("listSum");
                    if (startNum >= listSum) {
                        break; // 已经获取全部数据，退出循环
                    }
                } else {
                    System.out.println("获取房间列表接口调用失败: " + response.message());
                    break; // 请求失败，退出循环
                }
            }
            insertRoomListToDatabase(allRoomData);
            long start2 = System.currentTimeMillis();
            log.info(" 获取房间列表耗时：" + (start2 - start1));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private void insertRoomListToDatabase(List<Map<String, Object>> allRoomData) {
        List<LwgyJointDoor> roomDataList = new ArrayList<>();
        for (Map<String, Object> roomList : allRoomData) {

            LwgyJointDoor lwgyJointDoor = new LwgyJointDoor();
            String id = UUIDGenerator.generate();
            lwgyJointDoor.setId(id);
            lwgyJointDoor.setDoorNo((String) roomList.get("roomId"));
            lwgyJointDoor.setThirdRoomId((String) roomList.get("roomId"));
            lwgyJointDoor.setThirdRoomName((String) roomList.get("roomName"));
            lwgyJointDoor.setThirdFloorId((String) roomList.get("floorId"));
            lwgyJointDoor.setThirdFloorName((String) roomList.get("floorName"));
            lwgyJointDoor.setThirdBuildingId((String) roomList.get("buildingId"));
            lwgyJointDoor.setThirdBuildingName((String) roomList.get("buildingName"));
            lwgyJointDoor.setThirdHouseId((String) roomList.get("houseId"));
            lwgyJointDoor.setThirdHouseName((String) roomList.get("houseName"));
            lwgyJointDoor.setRoomState((Integer) roomList.get("roomState"));
            lwgyJointDoor.setElectricNum((Integer) roomList.get("electricNum"));
            lwgyJointDoor.setLockMac((String) roomList.get("lockMac"));
            lwgyJointDoor.setLockState((Integer)roomList.get("lockState"));
            lwgyJointDoor.setAesKey((String) roomList.get("aesKey"));
            lwgyJointDoor.setAdminAuthCode((String) roomList.get("adminAuthCode"));
            lwgyJointDoor.setTempAuthCode((String) roomList.get("tempAuthCode"));
            lwgyJointDoor.setGeneralAuthCode((String) roomList.get("generalAuthCode"));
            roomDataList.add(lwgyJointDoor);
        }
        doorLockService.insertThirdRoom(roomDataList);
        System.out.println("存入数据库成功");
    }
}
